﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;

namespace ImageTour
{
    class LineAnnotationTool : ImageAnnotationTool
    {
        private bool mouseButtonPressed = false;
        private int ox, oy;
        private int tx, ty;
        bool isAux = false;
        public LineAnnotationTool(bool isAux = false)
        {
            this.isAux = isAux;
        }
        internal override void DrawOverlay(Graphics g)
        {
            annotations.Draw(view, g);
            if (mouseButtonPressed)
            {
                g.DrawLine(Pens.Red, view.ImageSpacePointToScreenSpacePoint(new Point(ox, oy)),
                    view.ImageSpacePointToScreenSpacePoint(new Point(tx, ty)));
            }
        }

        internal override void MouseDown(int x, int y)
        {
            mouseButtonPressed = true;
            ox = x;
            oy = y;
            tx = ox;
            ty = oy;
        }

        internal override void MouseMove(int x, int y)
        {
            if (mouseButtonPressed)
            {
                tx = x;
                ty = y;
            }
        }

        internal override void MouseUp(int x, int y)
        {
            if (mouseButtonPressed)
            {
                mouseButtonPressed = false;
                var p1 = new Point(ox, oy);
                var p2 = new Point(x, y);

                annotations.Lines.Add(new LineAnnotation() { P1 = Snap(p1), P2 = Snap(p2), IsAux = isAux });
            }
        }

        private Point Snap(Point p1)
        {
            var p = new Float2(view.ImageSpacePointToScreenSpacePoint(p1));
            foreach (var l in annotations.Lines)
            {
                if ((new Float2(view.ImageSpacePointToScreenSpacePoint(l.P1)) - p).Length() < 4)
                    p1 = l.P1;
                if ((new Float2(view.ImageSpacePointToScreenSpacePoint(l.P2)) - p).Length() < 4)
                    p1 = l.P2;
            }
            if (p.y > view.ImageSpacePointToScreenSpacePoint(new Point(0,view.Image.Height)).Y - 4)
            {
                p1.Y = view.Image.Height;
            }
            if (p.x < view.ImageSpacePointToScreenSpacePoint(new Point(0, 0)).X + 4)
            {
                p1.X = 0;
            }
            if (p.x > view.ImageSpacePointToScreenSpacePoint(new Point(view.Image.Width, 0)).X - 4)
            {
                p1.X = view.Image.Width;
            }
            return p1;
        }
    }
}
